//
// Created by choumei on 2021/9/12.
//

#include "MyBuffer.h"

int MyBuffer::read(char *data, int qLen) {
    int tempWid = 0;
    int needCopyLen = 0;
    int realCopyLen = 0;
    while (tempWid < qLen) {
        if (this->wId == this->rId) {
            this->wId = 0;
            this->rId = 0;
            try {
                auto rLen = recv(this->sockfd, this->dataBuf, tempBufSize, 0);
                this->wId += rLen;
            } catch (...) {
                throw -1;
            }
        }
        needCopyLen = qLen - tempWid;
        realCopyLen = needCopyLen > this->wId - this->rId ? this->wId - this->rId : needCopyLen;
        memcpy(data + tempWid, this->dataBuf + this->rId, realCopyLen);
        this->rId += realCopyLen;
        tempWid += realCopyLen;
    }
    return tempWid;
}

MyBuffer::MyBuffer() {
    struct sockaddr_in servaddr;
    this->wId = 0;
    this->rId = 0;
    dataBuf = new char[tempBufSize];
    if ((this->sockfd = socket(AF_INET, SOCK_STREAM, 0)) < 0) {
        printf("create socket error: %s(errno: %d)\n", strerror(errno), errno);
        exit(0);
    }

    memset(&servaddr, 0, sizeof(servaddr));
    servaddr.sin_family = AF_INET;
    servaddr.sin_port = htons(8080);
    if (inet_pton(AF_INET, (const char *) "127.0.0.1", &servaddr.sin_addr) <= 0) {
        printf("inet_pton error for \n");
        exit(0);
    }

    if (::connect(sockfd, (struct sockaddr *) &servaddr, sizeof(servaddr)) < 0) {
        printf("connect error: %s(errno: %d)\n", strerror(errno), errno);
        exit(0);
    }
//    this->tcpSocket->connectToHost("127.0.0.1", 8080);
//    this->tcpSocket->waitForConnected();
//    connect(this->tcpSocket, &QTcpSocket::readyRead, this, [=]() {
//        mutex.lock();
//
//        mutex.unlock();
//    });
}

MyBuffer::~MyBuffer() {
//    delete this->tcpSocket;
    delete dataBuf;
}

void MyBuffer::receiveData() {

}

